(function(window, config) {

	var app = angular.module('app.service', []);
	app.factory('_API', ['$rootScope', '$location',
		function($rootScope, $location) {
			var api = {
				config: {
					'$rootScope': $rootScope,
					domain: $SDC.apiDomain
				}
			};
			
			var _commErrorCode = {};
			api.commWhen = function(errorCode, back) {
				_commErrorCode[errorCode] = back;
				return api;
			}
			
			api.ajax = function(path, data, loadingCon) {
				if (!data) {
					data = {};
				}
				data['_appType'] = "site";

				var map = {
					success: function() {},
					error: function() {
						return false
					},
					other: {}
				};

				var error = function(json) {
					// 针对自定义错误code
					json.msgInfo = json.msg + ' (' + json.code + ")";

					// 处理when
					var temp = map.other[json.code];
					if (!temp) {
						temp = _commErrorCode[json.code];
					}
					if (temp) {
						temp(json);
						return;
					}

					// 回调Error
					if (map.error(json)) { // 返回true 表示已处理错误Code
						return;
					}

					// 通用异常Code处理
					console.error(json, {path:path, data:data});
				};
				if (path.indexOf("/") != 0) {
					path = "/" + path;
				}

				//动画
				var el = null;
				if (loadingCon) {
					el = $(loadingCon);
				} else {
					el = $('#ngView');
				}
				var finish = function() {
					$rootScope.$apply();
					$SDC.unblockUI(el);
				};

				$SDC.blockUI({
					target: el
				})

				$.ajax({
					"url": api.config.domain + path + ".json",
					"dataType": "JSON",
					"data": data,
					"type": "POST",
					"cache": false,
					"timeout": 600000,
					"traditional": true,
					"xhrFields": {
						"withCredentials": true
					},
					"crossDomain": true,
					success: function(json) {
						if (json.code === 0) {
							map.success(json);
						} else {
							error(json);
						}
						finish();
					},
					error: function(json, status) {
						if (status == 'timeout') { // 超时,status还有success,error等值的情况
							error({
								code: -1001,
								msg: 'Ajax timeout'
							});
						} else {
							error({
								code: -1000,
								msg: 'Ajax error'
							});
						}
						finish();
					}
				});

				return {
					success: function(back) {
						map.success = back;
						return this;
					},
					error: function(back) {
						map.error = back;
						return this;
					},
					when: function(errorCode, back) {
						map.other[errorCode] = back;
						return this;
					}
				};
			};

			api.comm = function(path, data, loadingCon) {
				if (!data) {
					data = {};
				}
				return api.ajax(path, data, loadingCon);
			};

			return api;
		}
	]);

})(window);